package cn.com.pansky.action.bank;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.pansky.payment.PayConf;
import cn.com.pansky.service.OrderBackWriteService;
import cn.com.pansky.util.AppUtils;
import cn.com.pansky.util.RequestUtils;

/**
 * Servlet implementation class RecvNotify
 */
public class RecvNotify extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected static Logger logger = LoggerFactory.getLogger(RecvNotify.class);
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
		resp.setStatus(HttpServletResponse.SC_OK);// 响应清算平台通知
		
		//获取通知参数
		Map<String, String> respMap = RequestUtils.getReqMap(req);
		
		// 转换编码
		if(null != respMap.get("merReserved1")){
			String merReserved1 = respMap.get("merReserved1");
			if(StringUtils.isNotBlank(merReserved1)){
				respMap.put("merReserved1", new String(merReserved1.getBytes("ISO8859-1"), respMap.get("charset")));
			}
		}
		if(null != respMap.get("merReserved2")){
			String merReserved2 = respMap.get("merReserved2");
			if(StringUtils.isNotBlank(merReserved2)){
				respMap.put("merReserved2", new String(merReserved2.getBytes("ISO8859-1"), respMap.get("charset")));
			}
		}
		if(null != respMap.get("merReserved3")){
			String merReserved3 = respMap.get("merReserved3");
			if(StringUtils.isNotBlank(merReserved3)){
				respMap.put("merReserved3", new String(merReserved3.getBytes("ISO8859-1"), respMap.get("charset")));
			}
		}
		
		logger.info("接收到异步通知报文:" + respMap.toString());
		
		//签名验证
		boolean validate = AppUtils.validate(respMap, PayConf.SIGNKEY, respMap.get("charset"));
		resp.setContentType("text/html;charset=" + "UTF-8");
		resp.setCharacterEncoding("UTF-8");
		String str = "";
		if (validate) {
			logger.info("签名验证成功.");
			try {
	    		// 回填业务系统数据
	    		OrderBackWriteService os = new OrderBackWriteService();
	    		
	    		Map<String, String> map = new HashMap<String, String>();
	    		String orderAmount = respMap.get("orderAmount");
	    		// 将支付金额分转元
	    		BigDecimal amount = new BigDecimal(orderAmount);
	    		amount = amount.divide(new BigDecimal(100));
	    		
	    		map.put("AAE010", "999999"); // 当事人缴费账号
	    		map.put("bankType", "JH");
	    		map.put("AcqSsn", respMap.get("qid"));// 银行缴费流水号
	    		map.put("TranAmt", amount.toString());// 缴费金额  //
	    		map.put("TermSsn", respMap.get("orderNumber"));// 社保流水号
	    		map.put("AAC002", respMap.get("merReserved3"));//身份证号
	    		map.put("AAE011", respMap.get("merReserved2"));//代理人ID
				os.orderBackWrite(map);
	    		
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.info("回填业务系统失败.");
			}
			
			// 此处添加商户业务处理逻辑
			if ("1".equals(respMap.get("state"))) {
				logger.info("交易成功.");
				str = "	<img alt='' src='img/success.png' style='/* align-self: center; */.aligncenter "
		    			+ "{clear: both;display: block;margin:auto;  }.aligncenter {clear: both;display: "
		    			+ "block;margin:auto;  }clear: both;display: block;margin:auto;margin-top: 200px;'>"
		    			+ "<span class='title' style='text-align: center;clear: both;display: block;"
		    			+ "margin-top: 30px;font-size: 20px;width:100px, height:100px'>支付成功，金额 ¥ "+respMap.get("orderAmount")+"</span>";
				
			} else if ("2".equals(respMap.get("state"))) {
				logger.info("交易失败.");
				str = "<img alt='' src='img/error.png' style='/* align-self: center; */.aligncenter "
						+ "{clear: both;display: block;margin:auto;  }.aligncenter {clear: both;display: block;"
						+ "margin:auto;  }clear: both;display: block;margin:auto;margin-top: 200px;>"
						+ "<span class='title' style='text-align: center;clear: both;display: block;margin-top: 30px;"
						+ "font-size: 40px;'>支付失败</span><span style='text-align: center;clear: both;display: block;"
						+ "margin-top: 30px;font-size: 20px;width:100px, height:100px';margin-left: 100px;margin-right: 100px;'>如果银行已经扣款成功，"
						+ "请您次日在“我的”-“订单查询”查询订单支付信息！</span>";
			}
		} else {
			logger.info("签名验证失败.");
			// 此处添加商户业务处理逻辑
		}
		resp.getWriter().write(str);
	}
}
